/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.audit.controller;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.koron.audit.domain.Audit;
import com.koron.audit.service.api.AuditService;
import com.koron.audit.utils.BusinessCode;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.common.web.Util;
import com.koron.workflow.bean.MessageEntity;
import com.koron.workflow.bean.TaskListBean;
import com.koron.workflow.service.api.WorkflowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;

@Api(tags = "audit", description = "审批记录接口类")
@RestController
@RequestMapping("/audit")
public class AuditController {
    private final static   Logger logger = LoggerFactory.getLogger(AuditController.class);
    @Autowired
    private AuditService auditService;

    @Autowired
    private WorkflowService workflowService;

    @Autowired
    private Util util;

    @ApiOperation("获取所有审批记录，可按条件查询，分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "审批编号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "title", value = "标题", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "flowName", value = "流程名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "time", value = "时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "审批状态", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "int", paramType = "query")
    })
    @RequestMapping(value = "/list.htm", method = RequestMethod.POST)
    public MessageBean<DataBean> list(@RequestParam(required = false) final String code, @RequestParam(required = false) final String title, @RequestParam(required = false) final String flowName, @RequestParam(required = false) final
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy-MM-dd") Date time,
                                      @RequestParam(required = false) final Integer state, @RequestParam(required = true) Integer page,
                                      @RequestParam(required = true) Integer pageSize) {
        MessageBean<DataBean> msg = new MessageBean<>();
        Integer start = null;
        if (null != page) {
            if (pageSize != null) {
                if (pageSize <= 0)
                    pageSize = 10;
            }
            start = (page <= 1) ? 0 : (page - 1) * pageSize;
        }
        List<Audit> list = auditService.queryByCondition(code, title, flowName, time, state, start, pageSize);
        Integer totalNumber = auditService.countByCondition(code, title, flowName, time, state);
        Integer totalPage = totalNumber > pageSize ? (totalNumber % pageSize == 0 ? totalNumber / pageSize : totalNumber / pageSize + 1) : 1;
        DataBean<Audit> dataBean = new DataBean<>();
        dataBean.setList(list);
        dataBean.setTotalNumber(totalNumber);
        dataBean.setTotalPage(totalPage);
        msg.setData(dataBean);
        msg.setCode(BusinessCode.SUCCESS.getCode());
        msg.setDescription("获取审批记录列表成功");
        return msg;
    }

    @ApiOperation(value = "获取人员已发起的任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode", value = "当前登录人code,pc端不传，app端必传", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "审批编号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "title", value = "标题", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "flowName", value = "流程名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "审批状态", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "time", value = "时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键词", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "int", paramType = "query"),
    })
    @RequestMapping(value = "/queryByInitiator.htm", method = {RequestMethod.POST})
    public MessageBean<DataBean<Audit>> queryByInitiator(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                                         @RequestParam(required = false) final String userCode, @RequestParam(required = false) final String title,
                                                         @RequestParam(required = false) final String code, @RequestParam(required = false) final String flowName,
                                                         @RequestParam(required = false) final Integer state, @RequestParam(required = false) final @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
                                                         @DateTimeFormat(pattern = "yyyy-MM-dd") Date time, @RequestParam(required = false) String keyword, @RequestParam Integer page, @RequestParam Integer pageSize) {
        MessageBean<DataBean<Audit>> msg = new MessageBean<>();
        List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userCode, null).getData();
        if (null == user) {
            if (null != staffBeanList && staffBeanList.size() > 0)
                user = staffBeanList.get(0);
        }
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return msg;
        }
        Integer start = null;
        if (page == null || page <= 0) {
            page = 1;
            if (pageSize == null || pageSize <= 0) {
                pageSize = 15;
            }
        }
        start = (page <= 1) ? 0 : (page - 1) * pageSize;
        return auditService.queryByInitiator(user.getCode(), code, title, flowName, time, state, start, pageSize, keyword);
    }

    @ApiOperation(value = "获取人员待审任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode", value = "当前登录人code,pc端不传，app端必传", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "审批编号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "title", value = "标题", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "flowName", value = "流程名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "审批状态", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "time", value = "时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键词", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "int", paramType = "query"),
    })
    @RequestMapping(value = "/pendtask.htm", method = {RequestMethod.POST})
    public MessageBean<DataBean<Audit>> queryTaskByPend(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                                        @RequestParam(required = false) final String userCode, @RequestParam(required = false) final String code, @RequestParam(required = false) final String title,
                                                        @RequestParam(required = false) final String flowName, @RequestParam(required = false) final Integer state,
                                                        @RequestParam(required = false) final @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
                                                        @DateTimeFormat(pattern = "yyyy-MM-dd") Date time, @RequestParam(required = false) String keyword, @RequestParam Integer page, @RequestParam Integer pageSize) {
        MessageBean<DataBean<Audit>> msg = new MessageBean<>();
        try {
            List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userCode, null).getData();
            if (null == user) {
                if (null != staffBeanList && staffBeanList.size() > 0)
                    user = staffBeanList.get(0);
            }
            if (null == user) {
                msg.setCode(BusinessCode.NOT_LOGIN.getCode());
                msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
                return msg;
            }
            Integer start = 0;
            if (page != null && page > 0) {
                if (pageSize == null || pageSize <= 0) {
                    pageSize = 15;
                }
                start = (page - 1) * pageSize;
            }
           /* MessageBean<List<TaskListBean>> listMessageBean=workflowService.getWorkflowList(user.getCode(),2,null,0,1);
            //先去判断有多少条数据,取出所有数据
            Integer totalCount=((MessageEntity<List<TaskListBean>>) listMessageBean).getTotalCount();
            List<String>idList=new ArrayList<>();
            MessageBean<List<TaskListBean>> totalMessage=workflowService.getWorkflowList(user.getCode(),2,null,0,totalCount==null?20:totalCount);*/
            List<String> idList = new ArrayList<>();
            //String encode = URLEncoder.encode(user.getUserid(), "UTF-8");
            MessageEntity<?> totalMessage = workflowService.list(null, null, null,
                    null, null, null, 2, null, user.getUserid(), 0, Integer.MAX_VALUE);
            List<LinkedHashMap> taskList = (List<LinkedHashMap>) totalMessage.getData();
            Map<String, String> curNodeCodeMap = new HashMap();
            if (null != taskList && taskList.size() > 0) {
                for (LinkedHashMap map : taskList) {
                    String billId = (String) map.get("billId");
                    String curNodeCode = (String) map.get("curNodeCode");
                    idList.add(billId);
                    curNodeCodeMap.put(billId, curNodeCode);
                }
            }
//            if (totalCount>20){
//                int pageNo=totalCount%20==0?totalCount/20:totalCount/20+1;
//                for(int i=0;i<=pageNo;i++){
//                    MessageBean<List<TaskListBean>> listMessageBean1=workflowService.getWorkflowList(user.getCode(),2,null,i,totalCount);
//                    List<TaskListBean>taskList=listMessageBean1.getData();
//                    if (null!=taskList&&taskList.size()>0){
//                        idList.addAll(taskList.stream().map(TaskListBean::getBusinesskey).collect(Collectors.toList()));
//                    }
//                }
//            }else{
//                MessageBean<List<TaskListBean>> listMessageBean1=workflowService.getWorkflowList(user.getCode(),2,null,0,totalCount);
//                List<TaskListBean>taskList=listMessageBean1.getData();
//                if (null!=taskList&&taskList.size()>0){
//                    idList.addAll(taskList.stream().map(TaskListBean::getBusinesskey).collect(Collectors.toList()));
//                }
//            }
            if (null != idList && idList.size() > 0) {
                msg = auditService.queryByIdList(idList, code, title, flowName, 1, time, start, pageSize, keyword);
                if (null != msg.getData()) {
                    DataBean<Audit> data = msg.getData();
                    List<Audit> list = data.getList();
                    for (Audit audit : list) {
                        if (!curNodeCodeMap.get(audit.getId()).equals(audit.getNowNodeCode())) {
                            audit.setNowNodeCode(curNodeCodeMap.get(audit.getId()));
                        }
                    }
                }
                msg.getData().setPageNo(page);
                return msg;
            } else {
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription(BusinessCode.SUCCESS.getDescription());
                DataBean<Audit> dataBean = new DataBean<Audit>();
                dataBean.setList(null);
                dataBean.setPageSize(pageSize);
                dataBean.setTotalNumber(0);
                dataBean.setPageNo(page);
                msg.setData(dataBean);
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }

    }

    @RequestMapping(value = "/queryById.htm", method = {RequestMethod.GET})
    public MessageBean<Audit> queryById(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                        @RequestParam(required = false) final String id) {
        MessageBean<Audit> msg = new MessageBean<>();
        try {
            if (null == user) {
                msg.setCode(BusinessCode.NOT_LOGIN.getCode());
                msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
                return msg;
            }
            Audit audit = auditService.queryOne(id);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setData(audit);
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @ApiOperation(value = "获取人员已审任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode", value = "当前登录人code,pc端不传，app端必传", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "审批编号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "title", value = "标题", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "flowName", value = "流程名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "审批状态", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "time", value = "时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键词", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "int", paramType = "query"),
    })
    @RequestMapping(value = "/taskapproved.htm", method = {RequestMethod.POST})
    @ResponseBody
    public MessageBean<DataBean<Audit>> queryTaskApproved
            (@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
             @RequestParam(required = false) final String userCode, @RequestParam(required = false) final String title,
             @RequestParam(required = false) final String code, @RequestParam(required = false) final String flowName,
             @RequestParam(required = false) final Integer state,
             @RequestParam(required = false) final @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
             @DateTimeFormat(pattern = "yyyy-MM-dd") Date time, @RequestParam(required = false) String keyword,
             @RequestParam Integer page, @RequestParam Integer pageSize) {
        MessageBean<DataBean<Audit>> msg = new MessageBean<>();
        try {
            List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userCode, null).getData();
            if (null == user) {
                if (null != staffBeanList && staffBeanList.size() > 0)
                    user = staffBeanList.get(0);
            }
            if (null == user) {
                msg.setCode(BusinessCode.NOT_LOGIN.getCode());
                msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
                return msg;
            }
            Integer start = 0;
            if (page != null && page > 0) {
                if (pageSize == null || pageSize <= 0) {
                    pageSize = 15;
                }
                start = (page - 1) * pageSize;
            }

            List<String> idList = new ArrayList<>();
            //String encode = URLEncoder.encode(user.getUserid(), "UTF-8");

            MessageEntity<?> totalMessage = workflowService.list(null, null, null,
                    null, null, null, 5, null, user.getUserid(), 0, Integer.MAX_VALUE);
            List<LinkedHashMap> taskList = (List<LinkedHashMap>) totalMessage.getData();
            if (null != taskList && taskList.size() > 0) {
                for (LinkedHashMap map : taskList) {
                    String billId = (String) map.get("billId");
                    idList.add(billId);
                }
            }

            if (null != idList && idList.size() > 0) {
                msg = auditService.queryByIdList(idList, code, title, flowName, null, time, start, pageSize, keyword);
                msg.getData().setPageNo(page);
                return msg;
            } else {
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription(BusinessCode.SUCCESS.getDescription());
                DataBean<Audit> dataBean = new DataBean<Audit>();
                dataBean.setList(null);
                dataBean.setPageSize(pageSize);
                dataBean.setTotalNumber(0);
                dataBean.setPageNo(page);
                msg.setData(dataBean);
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @ApiOperation(value = "获取工作流任务情况")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "staffcode", value = "当前登录人code,pc端不传，app端必传", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "type 1我发起的 2待审 3参与的 4沟通 5结束", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "templateKey", value = "", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "int", paramType = "query"),
    })
    @RequestMapping(value = "/getWorkflowList.htm", method = {RequestMethod.POST})
    @ResponseBody
    public MessageBean<List<TaskListBean>> getWorkflowList
            (@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String staffcode, Integer type, String
                    templateKey,
             Integer page, Integer pageSize) throws Exception {
        MessageBean<List<TaskListBean>> msg = new MessageEntity<>();
        if (StringUtils.isEmpty(staffcode) && user == null) {
            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return msg;
        }
        if (StringUtils.isEmpty(staffcode))
            staffcode = user.getCode();
        msg = workflowService.getWorkflowList(staffcode, type, templateKey, page, pageSize);
        return msg;
    }

    private String getNextCandidateUser(List<Map> list) {

        String nextUser = "";
        String time = (String) list.get(0).get("nowEndTime");
        int ci = 0;
        for (int i = 0; i < list.size(); i++) {
            String newtime = (String) list.get(i).get("nowEndTime");
            int compre = time.compareTo(newtime);
            if (compre < 0) {
                ci = i;
                time = newtime;
            }
        }
        String nexttaskId = (String) list.get(ci).get("nexttaskId");
        if (StringUtils.isNotBlank(nexttaskId)) {
            return (String) list.get(ci).get("nextcandidateUsers");
        } else {
            return "error";
        }

    }

    private String getIsExists(List<Map> list, String userCode) {

        String result = "0";
        for (int i = 0; i < list.size(); i++) {
            String nowAssignee = (String) list.get(i).get("nowAssignee");
            if (nowAssignee.equals(userCode)) {
                result = "1";
            }

        }
        return result;
    }

}

